<template>
  <div v-loading="pageLoading">
    <el-row>
      <el-col class="col-wrap" :span="8">
        <SelectSupply
          v-if="canSelectSupply"
          :supply-edit-name="supplierInfo.supplierName"
          :before-select="confirmSupplierPrompt"
          @getName="updateSupplierInfo"
        />
        <template v-else>
          <TextTooltip label="供应商" :textContent="supplierInfo.supplierName" />
        </template>
      </el-col>
      <el-col class="col-wrap" :span="8">
        <ListPopover label="供货城市" :dataList="supplyCitiesInfo.list" :content="supplyCitiesInfo.names">
          <template #li-item="slotProps">
            <span>{{ slotProps.item.cityName }} {{ slotProps.item.cityCode }}</span>
          </template>
        </ListPopover>
      </el-col>
      <el-col class="col-wrap" :span="8">
        <TextTooltip label="销售区域" :textContent="salesArea.names" />
        <el-button
          v-if="canSetArea"
          type="text"
          size="large"
          @click="handleSelectArea"
        >选择区域
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-col class="col-wrap" :span="8">
        <TextTooltip label="供应商管理区域" :textContent="supplierInfo.supManagerHrAreaName" />
      </el-col>
      <el-col class="col-wrap" :span="8">
        <TextTooltip label="供应商归属部门" :textContent="supplierInfo.purchaseAttributionName" />
      </el-col>
    </el-row>
    <SalesAreaDialog
      :visible.sync="salesArea.visible"
      :cityList="salesArea.list"
      :selectCitys="salesArea.codes"
      :before-select="confirmAreaPrompt"
      @getSaleAreas="updateSaleAreaInfo"
    />
  </div>
</template>
<script>
import SelectSupply from '@/components/commodity/getSupply';
import ListPopover from '@/components/ShowContent/ListPopover';
import TextTooltip from '@/components/ShowContent/TextTooltip';
import SalesAreaDialog from '@/components/SalesAreaDialog';
import { EVENT_BUS } from '../constants';
import {
  getSupplyProvinceBySupplyNoService,
  queryLoginUserSaleAreaService,
  queryBusinessAreaListService
} from '@/api/public'; // 获取售卖平台及销售区域
export default {
  components: {
    SelectSupply,
    ListPopover,
    TextTooltip,
    SalesAreaDialog
  },
  props: {
    dataSource: {
      type: Object,
      default: () => ({})
    },
    canSelectSupply: {
      type: Boolean,
      default: true
    },
    canSetArea: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      supplierInfo: {},
      supplyCitiesInfo: {
        list: [],
        names: ''
      },
      pageLoading: false,
      salesArea: {
        visible: false,
        names: '',
        codes: [],
        list: [],
      },
    }
  },
  created () {
    this.setSalesAreaInfo()
    this.setAreaInfo()
  },
  methods: {
    // 选择区域
    handleSelectArea () {
      this.salesArea.visible = true
    },
    // 当前供应商与已有供应商是否一致
    isSameSupplier (supplyInfo) {
      const isConsitent = supplyInfo?.supplierCode == this.supplierInfo?.supplierCode
      return isConsitent
    },
    // 确认供应商提示
    confirmSupplierPrompt (onSuccess, supplyInfo) {
      if (this.isSameSupplier(supplyInfo)) return onSuccess() // 如果关联编码等于已有编码，则供应商没有变更
      if (!EVENT_BUS._data?.canOperatePurchase) return onSuccess() // 不能操作进价信息时，无需提示是否确认
      const content = '如果重新选择供应商，进价信息会被清空，确认选择吗？'
      this.$confirm(content, '提示', { type: 'warning' })
        .then(() => { onSuccess() })
        .catch(() => {})
    },
    // 确认区域提示
    confirmAreaPrompt (onSuccess, areaCodes) {
      const isSameArea =
        this.salesArea.codes.every(item => areaCodes.includes(item))
        && this.salesArea.codes.length == areaCodes.length
      if (isSameArea) return onSuccess() // 如果区域编码等于已有编码，则销售区域没有变更
      if (!EVENT_BUS._data?.canOperatePurchase) return onSuccess() // 不能操作进价信息时，无需提示是否确认
      const content = '如果重新选择销售区域，进价信息会被清空，确认选择吗？'
      this.$confirm(content, '提示', { type: 'warning' })
        .then(() => { onSuccess() })
        .catch(() => {})
    },
    // 更新供应商信息
    updateSupplierInfo (info) {
      const isNoChangeSupplier = this.supplierInfo?.supplierCode && this.isSameSupplier(info)
      if (isNoChangeSupplier) return // 如果关联编码等于已有编码，则供应商没有变更
      this.supplierInfo = info
      this.updateSupplyCitiesInfo()
      const supplierInfo = {
        supplyUuid: info?.supplierCode,
        supplyName: info?.supplierName,
        saleAreaNos: EVENT_BUS._data.saleAreaNos,
      }
      const taxRateInvoiceInfo = _.pick(info, ['taxRate', 'invoiceType', 'invoiceTypeName'])
      EVENT_BUS.$emit('change-supplier', { supplierInfo, taxRateInvoiceInfo })
    },
    // 更新供货城市信息
    async updateSupplyCitiesInfo () {
      const data = { supplierCode: this.supplierInfo.supplierCode }
      const loadingFn = state => { this.pageLoading = state }
      const res = await getSupplyProvinceBySupplyNoService(data, loadingFn)
      this.supplyCitiesInfo.list = (res?.retData ?? [])
      this.supplyCitiesInfo.names = this.supplyCitiesInfo.list.map(item => item.cityName).join(',')
    },
    // 设置销售区域信息
    async setSalesAreaInfo () {
      const loadingFn = state => { this.pageLoading = state }
      const res = await queryLoginUserSaleAreaService({}, loadingFn)
      this.salesArea.names = res?.retData?.shortName
      this.salesArea.codes = res?.retData?.areaCode ? [res?.retData?.areaCode] : []
      const saleAreaInfo = {
        name: res?.retData?.shortName,
        code: res?.retData?.areaCode
      }
      EVENT_BUS._data.saleAreaNos = res?.retData?.areaCode ? [res.retData.areaCode] : []
      EVENT_BUS.$emit('get-salearea', saleAreaInfo )
    },
    // 设置销售区域信息
    async setAreaInfo () {
      const res = await queryBusinessAreaListService()
      this.salesArea.list = res?.retData ?? []
    },
    // 更新销售区域信息
    updateSaleAreaInfo (areaCodes) {
      const isNoChangeArea =
        this.salesArea.codes.every(item => areaCodes.includes(item))
        && this.salesArea.codes.length == areaCodes.length
      if (isNoChangeArea) return // 如果区域编码等于已有编码，则销售区域没有变更
      this.salesArea.names = this.salesArea.list
        .filter(item => areaCodes.includes(item.areaCode))
        .map(item => item.shortName)
        .join('')
      this.salesArea.codes = areaCodes
      EVENT_BUS._data.saleAreaNos = areaCodes
      EVENT_BUS.$emit('change-areas', areaCodes)
    },
  }
}
</script>
<style lang="less" scoped>
.col-wrap {
  display: flex;
  align-items: center;
  min-height: 40px;
}
.show-content {
  max-width: 200px;
  color: #85888e;
  font-size: 13px;
}
</style>
